#ifndef UPLOADWORKER_H
#define UPLOADWORKER_H

#include <QObject>
#include <QTcpSocket>
#include <QThread>
#include <QTime>
#include <QTimer>

#include "UploadConfig.h"

namespace Upload {

class UploadWorker : public QObject
{
    Q_OBJECT
public:
    explicit UploadWorker(const QString &id, const Config &config, QObject *parent = nullptr);
    ~UploadWorker();

public slots:
    void start();
    void stop();

signals:
    void uploadSuccess(const QString &id, const QString &data);
    void uploadError(const QString &id, const QString &error);
    void statusChanged(const QString &id, bool running);

private slots:
    void uploadData();
    void onConnected();
    void onDisconnected();
    void onError(QAbstractSocket::SocketError error);
    void onDataSent();
    void retryUpload();

private:
    void connectToServer();
    void sendDataWithRetry(const QString &data, int recordId = -1);
    void scheduleRetry(const QString &errorMessage);
    QString buildUploadData();

    QString m_id;
    Config m_config;
    QTimer *m_timer;
    QTimer *m_retryTimer;
    QTime m_currentTime;
    QTcpSocket *m_socket;
    bool m_running;
    bool m_connected;

    QString m_pendingData;
    int m_retryCount;
    int m_maxRetryCount;
    int m_retryInterval;
    int m_currentRecordId;
};

}  // namespace Upload

#endif  // UPLOADWORKER_H